import { Alert, Checkbox, Icon, Tooltip, Input, Button, Message } from 'antd'
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale'
import React, { Component } from 'react'
import classnames from 'classnames'
// import Link from 'umi/link'
import { connect } from 'dva'
import md5 from 'md5'
import LoginComponents from './components/Login'
import styles from './style.less'

const { UserName, Password, Submit } = LoginComponents

@connect(({ login, loading }) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
  validting: loading.effects['login/smsValidator']
}))
class Login extends Component {
  loginForm = undefined

  state = {
    type: 'account',
    autoLogin: true,
    showQr: false,
    //
    validValue: ''
  }

  componentDidMount () {
    //
  }

  componentDidUpdate (prevProps) {
    if (prevProps.userLogin.status === 'needValid' && this.props.userLogin.status !== 'needValid') {
      this.setState({
        validValue: ''
      })
    }
  }

  changeAutoLogin = e => {
    this.setState({
      autoLogin: e.target.checked,
    })
  }

  handleSubmit = (err, values) => {
    // const { type } = this.state

    if (!err) {
      const { dispatch } = this.props
      values.password = md5(values.password)
      dispatch({
        type: 'login/login',
        payload: values,
      })
    }
  }

  handleValid = () => {
    let { validValue } = this.state
    let { dispatch } = this.props
    validValue = validValue.replace(/^\s+|\s+$/gm, '')
    if (validValue === '') {
      return Message.error('验证码不能为空')
    }
    // console.log('handleValid', this.state.validValue)
    dispatch({
      type: 'login/smsValidator',
      payload: {
        code: validValue
      }
    })
  }

  handleValidInputChange = (e) => {
    this.setState({
      validValue: e.target.value
    })
  }

  onTabChange = showQr => {
    this.setState({
      showQr,
    })
    if (showQr) {
      const { dispatch } = this.props
      dispatch({
        type: 'login/getQrcodeData',
        payload: {
          callback: res => {
            window.WwLogin({
              id: 'wx_reg',
              href: '',
              ...res.data,
            });
          },
        },
      })
    }
  }

  renderMessage = content => (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  )

  renderTabContent = () => {
    const { userLogin, submitting } = this.props
    const { status, type: loginType } = userLogin
    const { autoLogin, showQr } = this.state

    return (
      <React.Fragment>
        <div className={classnames(styles.loginTab, showQr ? styles.divHide : '')}>
          <div className={styles.loginTab_title}>登录</div>
          {status === 'error' &&
            loginType === 'account' &&
            !submitting &&
            this.renderMessage(
              formatMessage({
                id: 'user-login.login.message-invalid-credentials',
              }),
            )}
          <UserName
            name="account"
            placeholder="用户名"
            rules={[
              {
                required: true,
                message: formatMessage({
                  id: 'user-login.userName.required',
                }),
              },
            ]}
          />
          <Password
            name="password"
            placeholder="密码"
            rules={[
              {
                required: true,
                message: formatMessage({
                  id: 'user-login.password.required',
                }),
              },
            ]}
            onPressEnter={e => {
              e.preventDefault()

              if (this.loginForm) {
                this.loginForm.validateFields(this.handleSubmit)
              }
            }}
          />
          <div style={{ paddingTop: '5px' }}>
            <Checkbox checked={autoLogin} onChange={this.changeAutoLogin}>
              记住账号
            </Checkbox>
            <Tooltip title="请联系管理员修改密码">
              <a
                style={{
                  float: 'right',
                }}
              >
                <FormattedMessage id="user-login.login.forgot-password" />
              </a>
            </Tooltip>
          </div>
          <Submit loading={submitting}>
            <FormattedMessage id="user-login.login.login" />
          </Submit>
        </div>
        <div className={classnames(styles.loginTab, showQr ? '' : styles.divHide)}>
          <div id="wx_reg" className={styles.qr_box}>
          </div>
        </div>
      </React.Fragment>
    )
  }

  render () {
    const { userLogin, submitting, validting } = this.props
    const { status } = userLogin
    const { type, showQr } = this.state
    return (
      <React.Fragment>
        {
          status === 'needValid'
            ? <div className={classnames(styles.main, styles.animate__flipInY, styles.animate__animated)}>
              <div className={styles.valid_box}>
                <div className={styles.valid_title}>请输入短信验证码</div>
                <Input className={styles.valid_input} maxLength={10} onChange={this.handleValidInputChange} size="large" placeholder="请输入验证码" />
                <Button disabled={validting} className={styles.valid_btn} size="large" type="primary" onClick={this.handleValid}>提交</Button>
              </div>
            </div>
            : <div className={styles.main}>
              <LoginComponents
                defaultActiveKey={type}
                onSubmit={this.handleSubmit}
                onCreate={form => {
                  this.loginForm = form
                }}
              >
                <div
                  className={styles.changeTab_btn}
                  onClick={() => {
                    this.onTabChange(!showQr)
                  }}
                >
                  {showQr ? <Icon type="user" /> : <Icon type="qrcode" />}
                </div>
                <div className={styles.tab_btn_mask}></div>
                {this.renderTabContent()}
              </LoginComponents>
            </div>
        }
      </React.Fragment>
    )
  }
}

export default Login
